#include "BlogDetailsPage.h"

BlogDetailsPage::BlogDetailsPage(QWidget *parent)
    : QWidget{parent},
      likeCount(0),
      commentCount(0),
      favoriteCount(0),
      isFollowed(false),
      isLiked(false),
      isCollected(false),
      isBan(false)
{
    setupUI();
    setupUIButtonStyle();
    connectSignals();
}

void BlogDetailsPage::setupUI()
{
    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true); // 自动调整内部控件大小

    // 创建内容容器
    QWidget *contentWidget = new QWidget;
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);

    // 设置标题标签
    QHBoxLayout *topInfoLayout = new QHBoxLayout();
    titleLabel = new QLabel("文章标题", this);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold;");
    editButton = new QPushButton("✍ 编辑文章", this);
    deleteButton = new QPushButton("⛔ 删除文章", this);
    // 设置按钮样式
    QString buttonStyle = R"(
        QPushButton {
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 15px;
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QPushButton:pressed {
            background-color: #d0d0d0;
        }
    )";
    editButton->setFixedSize(110, 30);
    editButton->setStyleSheet(buttonStyle);
    deleteButton->setFixedSize(110, 30);
    deleteButton->setStyleSheet(buttonStyle);
    topInfoLayout->addWidget(titleLabel);
    topInfoLayout->addStretch();
    topInfoLayout->addWidget(editButton);
    topInfoLayout->addWidget(deleteButton);
    contentLayout->addLayout(topInfoLayout);

    // 添加小字行：更新时间、阅读量、文章分类等信息
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm");
    infoLabel = new QLabel(QString("更新时间: %1 | 阅读量: 0 | 分类: 计算机").arg(currentTime), this);
    infoLabel->setStyleSheet("font-size: 12px; color: gray;");
    contentLayout->addWidget(infoLabel);

    // 创建用户信息容器（头像 + 用户名）
    QWidget *userContainer = new QWidget(this);
    QHBoxLayout *userLayout = new QHBoxLayout(userContainer);
    userLayout->setContentsMargins(0, 0, 0, 0);
    userLayout->setSpacing(8); // 设置头像与文字间距

    AvatarLabel *avatarLabel = new AvatarLabel(this);
    avatarLabel->setFixedSize(50, 50);
    userLayout->addWidget(avatarLabel);

    avatarLabel->setPixmap(QPixmap(":/test/resoures/test/avatar1.png"));

    // 创建用户名 QLabel
    QLabel *usernameLabel = new QLabel("脸滚键盘1201", this);
    usernameLabel->setStyleSheet("font-size: 14px;");
    userLayout->addWidget(usernameLabel);

    // 创建 userButton 并设置布局
    userButton = new QPushButton(this);
    userButton->setFixedHeight(50);    // 固定高度
    userButton->setFlat(true);         // 去除按钮样式干扰
    userButton->setLayout(userLayout); // 将带头像和文字的 widget 设为按钮内容

    followButton = new QPushButton("关注", this);
    followButton->setFixedSize(80, 40);

    // 将 userButton 和 followButton 放入一行
    QWidget *authorRow = new QWidget(this);
    QHBoxLayout *rowLayout = new QHBoxLayout(authorRow);
    rowLayout->setContentsMargins(0, 0, 0, 0);
    rowLayout->addWidget(userButton, 1);                   // 可伸缩空间
    rowLayout->addWidget(followButton, 0, Qt::AlignRight); // 关注按钮右对齐

    contentLayout->addWidget(authorRow);

    // 创建文章内容区域
    contentBrowser = new QTextBrowser(this);
    contentBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    contentLayout->addWidget(contentBrowser);

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    downloadButton = new QPushButton("附件下载", this);
    likeButton = new QPushButton(QString("👍点赞 %1").arg(likeCount), this);
    commentButton = new QPushButton(QString("💬评论 %1").arg(commentCount), this);
    collectButton = new QPushButton(QString("⭐收藏 %1").arg(favoriteCount), this);
    reportButton = new QPushButton("❗ 举报", this);

    buttonLayout->addWidget(downloadButton);
    buttonLayout->addWidget(likeButton);
    buttonLayout->addWidget(commentButton);
    buttonLayout->addWidget(collectButton);
    buttonLayout->addWidget(reportButton);

    contentLayout->addLayout(buttonLayout);

    // 创建评论列表
    commentList = new CommentListWidget(this);
    contentLayout->addWidget(commentList);

    // 将内容容器设置到滚动区域中
    scrollArea->setWidget(contentWidget);

    // 设置主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(scrollArea); // 将滚动区域添加到主布局中

    setEditAndDeleteButtonVisible(true);
    setDownloadButtonVisible(true);
}

void BlogDetailsPage::connectSignals()
{
    connect(downloadButton, &QPushButton::clicked, this, &BlogDetailsPage::onDownloadClicked);
    connect(likeButton, &QPushButton::clicked, this, &BlogDetailsPage::onLikeClicked);
    connect(commentButton, &QPushButton::clicked, this, &BlogDetailsPage::onCommentClicked);
    connect(collectButton, &QPushButton::clicked, this, &BlogDetailsPage::onCollectClicked);
    connect(reportButton, &QPushButton::clicked, this, &BlogDetailsPage::onReportClicked);
    connect(userButton, &QPushButton::clicked, this, &BlogDetailsPage::onAuthorClicked);
    connect(followButton, &QPushButton::clicked, this, &BlogDetailsPage::onFollowClicked);
    connect(editButton, &QPushButton::clicked, this, &BlogDetailsPage::onEditClicked);
}

void BlogDetailsPage::onDownloadClicked()
{
    // 弹出确认支付对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认支付", "确认支付5元下载附件？",
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes)
    {
        // 用户点击了确定，弹出文件夹选择对话框
        QString folderPath = QFileDialog::getExistingDirectory(this, "选择下载位置", QString());

        if (!folderPath.isEmpty())
        {
            // 假设附件名称为 示例附件.zip
            QString fileName = "示例附件.zip";
            QString filePath = folderPath + "/" + fileName;

            // 模拟下载：创建一个空文件作为示例
            QFile file(filePath);
            if (file.open(QIODevice::WriteOnly))
            {
                file.close();
                QMessageBox::information(this, "下载成功", "附件已保存至指定文件夹！");
            }
            else
            {
                QMessageBox::critical(this, "错误", "无法保存文件到指定目录！");
            }
        }
    }
}

void BlogDetailsPage::onLikeClicked()
{
    isBan = false;
    isLiked = !isLiked;
    likeCount += isLiked ? 1 : -1;
    likeButton->setText(QString("👍点赞 %1").arg(likeCount));
    updateButtonStyle(likeButton, isLiked);
}

void BlogDetailsPage::onCommentClicked()
{
    if (isUserBanned())
    {
        QMessageBox::warning(this, "警告", "您的帐户受限，无法使用该功能");
        isBan = false;
        return;
    }
    InputDialog dialog("发表评论", "输入评论", this);
    if (dialog.exec() == QDialog::Accepted)
    {
        QString comment = dialog.getInputText();
        if (!comment.isEmpty())
        {
            // TODO: 提交评论到服务器或本地处理
            commentCount++;
            commentButton->setText(QString("💬评论 %1").arg(commentCount));
            qDebug() << "发表评论：" << comment;
            commentList->load(DataAccess::getCommentListByNew());
            isBan = true;
        }
    }
}

void BlogDetailsPage::onCollectClicked()
{
    isBan = false;
    isCollected = !isCollected;
    favoriteCount += isCollected ? 1 : -1;
    collectButton->setText(QString("⭐收藏 %1").arg(favoriteCount));

    updateButtonStyle(collectButton, isCollected);
}

void BlogDetailsPage::onReportClicked()
{
    InputDialog dialog("举报文章", "举报理由", this);
    if (dialog.exec() == QDialog::Accepted)
    {
        QString reason = dialog.getInputText();
        if (!reason.isEmpty())
        {
            // TODO: 提交举报到服务器或本地处理
            QMessageBox::information(this, "提示", "举报提交成功！");
            qDebug() << "举报理由：" << reason;
        }
    }
}

void BlogDetailsPage::onFollowClicked()
{
    isFollowed = !isFollowed;
    followButton->setText(isFollowed ? "已关注" : "关注");
    updateButtonStyle(followButton, isFollowed);
}

void BlogDetailsPage::onAuthorClicked()
{
    emit authorProfileRequested(); // 发送跳转信号
}

void BlogDetailsPage::onEditClicked()
{
    QString title = titleLabel->text();
    QString htmlContent = contentBrowser->toHtml();
    emit editRequested(title, htmlContent); // 发送跳转信号
}

void BlogDetailsPage::setTitle(const QString &title)
{
    titleLabel->setText(title);
}

void BlogDetailsPage::setContent(const QString &htmlContent)
{
    contentBrowser->setHtml(htmlContent);
    contentBrowser->setFixedHeight(contentBrowser->document()->size().height());
}

void BlogDetailsPage::setByDataModel(const BlogDetail &blogDetail)
{
    titleLabel->setText(blogDetail.title);
    infoLabel->setText(QString("更新时间: %1 | 阅读量: %2 | 分类: %3")
                           .arg(blogDetail.time)
                           .arg(blogDetail.readCount)
                           .arg(blogDetail.category));
    contentBrowser->setHtml(blogDetail.htmlContent);
    contentBrowser->setFixedHeight(contentBrowser->document()->size().height());
    likeButton->setText(QString("👍点赞 %1").arg(blogDetail.likeCount));
    commentButton->setText(QString("💬评论 %1").arg(blogDetail.commentCount));
    collectButton->setText(QString("⭐收藏 %1").arg(blogDetail.favoriteCount));
}

void BlogDetailsPage::setupUIButtonStyle()
{
    // 统一按钮样式
    QString buttonStyle = "QPushButton {"
                          "border: 1px solid #ccc;"
                          "border-radius: 8px;"
                          "padding: 6px 12px;"
                          "font-size: 14px;"
                          "background-color: #f5f5f5;"
                          "}"
                          "QPushButton:hover {"
                          "background-color: #e0e0e0;"
                          "}";
    downloadButton->setStyleSheet(buttonStyle);
    likeButton->setStyleSheet(buttonStyle);
    commentButton->setStyleSheet(buttonStyle);
    collectButton->setStyleSheet(buttonStyle);
    reportButton->setStyleSheet(buttonStyle);
    followButton->setStyleSheet(buttonStyle);
}

void BlogDetailsPage::updateButtonStyle(QPushButton *button, bool isActive)
{
    QString buttonStyleIsNotActive = "QPushButton {"
                                     "border: 1px solid #ccc;"
                                     "border-radius: 8px;"
                                     "padding: 6px 12px;"
                                     "font-size: 14px;"
                                     "background-color: #f5f5f5;"
                                     "}"
                                     "QPushButton:hover {"
                                     "background-color: #e0e0e0;"
                                     "}";

    QString buttonStyleIsActive = "QPushButton {"
                                  "border: 1px solid #0056b3;"
                                  "border-radius: 8px;"
                                  "padding: 6px 12px;"
                                  "font-size: 14px;"
                                  "background-color: #66ccff;"
                                  "}"
                                  "QPushButton:hover {"
                                  "background-color: #007BFF;"
                                  "}";

    if (isActive)
    {
        button->setStyleSheet(buttonStyleIsActive);
    }
    else
    {
        button->setStyleSheet(buttonStyleIsNotActive);
    }
}

void BlogDetailsPage::setEditAndDeleteButtonVisible(bool isVisible)
{
    editButton->setVisible(isVisible);
    deleteButton->setVisible(isVisible);
}

bool BlogDetailsPage::isUserBanned()
{
    return isBan;
}

void BlogDetailsPage::setDownloadButtonVisible(bool isVisible)
{
    downloadButton->setVisible(isVisible);
}

void BlogDetailsPage::clearComment()
{
    commentList->clear();
}